//
//  SocketUtil.m
//  Mahjong
//
//  Created by 饶首建 on 17/5/23.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "SocketUtil.h"

#import "GCDAsyncSocket.h"

@interface SocketUtil()<GCDAsyncSocketDelegate>

@property (nonatomic,strong) GCDAsyncSocket *socket;

@property (nonatomic) GCDAsyncSocket*serverSocket;




@end

@implementation SocketUtil

-(void)connect{
    NSError *error =nil;
    _serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    BOOL result = [self.serverSocket acceptOnPort:8080 error:&error];
    if(result && error ==nil) {
        //开放成功
        Log(@"开放成功");
    }
    

    
    //创建一个socket对象
    //dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //连接
    
    [_socket connectToHost:@"192.168.1.113" onPort:8080 error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
}
#pragma mark GCDAsyncSocketDelegate

#pragma mark 连接成功
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    NSLog(@"%s",__func__);
}


#pragma mark 断开连接
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    if (err) {
        NSLog(@"连接失败");
    }else{
        NSLog(@"正常断开");
    }
}

#pragma mark 数据发送成功
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"%s",__func__);
    //发送完数据手动读取，-1不设置超时
    [sock readDataWithTimeout:-1 tag:tag];
}

#pragma mark 读取数据
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSString *receiverStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%s %@",__func__,receiverStr);
}

@end
